<template>
  <a-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <template slot="footer">
      <a-button key="back" @click="handleCancel">关闭</a-button>
      <a-button v-if="title != '详情'" key="submit" type="primary" @click="handleSubmit">确认</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <div style="height: 50px; border-bottom: 1px solid #ccc; font-size: 24px; margin-bottom: 20px">
          身份证信息
          <a-button type="primary" @click="fetchIdCard" icon="plus" style="margin-left: 20px">读取身份证 </a-button>
        </div>
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="姓名">
              <a-input placeholder="请输入姓名" v-decorator="['realname', validatorRules.realname]" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="性别">
              <a-select placeholder="请选择性别" v-decorator="['sex', {}]">
                <a-select-option v-for="item in sexList" :key="item.value">{{ item.text }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="民族" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入民族" v-decorator="['national', {}]" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="出生日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-date-picker
                style="width: 100%"
                placeholder="请选择出生日期"
                format="YYYY-MM-DD"
                v-decorator="['birthday', {}]"
                @change="computedAge"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="年龄" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number placeholder="请输入年龄" v-model="age" :min="0" style="width: 100%" disabled />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="籍贯" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入籍贯" v-decorator="['nativePlace', {}]" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="身份证号">
              <a-input placeholder="请输入身份证号" v-decorator="['idCardNumber', {}]" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="发证机关" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入发证机关" v-decorator="['issuingAuthority', {}]" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="身份证有效期">
              <a-range-picker
                @change="onTimeChangeShen"
                v-model="dateRangeShen"
                format="YYYY-MM-DD"
                :placeholder="['开始时间', '结束时间']"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-item label="身份证正面" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <div style="width: 165px; height: 100px" :class="hadPhotoZ ? 'had' : 'nohad'">
                <img :src="'data:image/png;base64,' + photoZ" style="width: 165px; height: 100px" v-if="photoZ" />
                <div style="width: 165px; height: 100px" v-if="!photoZ"></div>
              </div>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="身份证反面" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <div style="width: 165px; height: 100px" :class="hadPhotoF ? 'had' : 'nohad'">
                <img :src="'data:image/png;base64,' + photoF" style="width: 165px; height: 100px" v-if="photoF" />
                <div style="width: 165px; height: 100px" v-if="!photoF"></div>
              </div>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </a-modal>
</template>
<script>
import { initDictOptions, filterDictText } from '@/components/dict/JDictSelectUtil'
import moment from 'moment'
import { putAction } from '@/api/manage'
export default {
  name: 'updateIdcard',
  data() {
    return {
      hadPhotoZ:true,
      hadPhotoF:true,
      dateRangeShen: [], //证件有效期
      age: '',
      sexList: [],
      photoF: '',
      photoZ: '',
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 17 },
      },
      form: this.$form.createForm(this),
      title: '更新身份证信息',
      visible: false,
      confirmLoading: false,
      validatorRules: {
        realname: { rules: [{ required: true, message: '请输入姓名!' }] },
        username: { rules: [{ required: true, message: '请输入用户账号!' }] },
        password: {
          age: { rules: [{ required: true, message: '请输入年龄!' }] },
          sex: { rules: [{ required: true, message: '请选择性别!' }] },
          idNumber: { rules: [{ required: true, message: '请输入身份证号!' }] },
          national: { rules: [{ required: true, message: '请输入民族!' }] },
          nativePlace: { rules: [{ required: true, message: '请输入籍贯!' }] },
          issuingAuthority: { rules: [{ required: true, message: '请输入发证机关!' }] },
          validityBegin: { rules: [{ required: true, message: '请选择有效期开始!' }] },
          validityEnd: { rules: [{ required: true, message: '请选择有效期结束!' }] },
        },
      },
      url: {
        update: '/sys/user/editIDCardInfo',
      },
    }
  },
  methods: {
    moment,
    /*时间区间*/
    onTimeChangeShen(date, dateString) {
      if (dateString) {
        this.validityBegin = dateString[0]
        this.validityEnd = dateString[1]
      }
    },
    computedAge(e) {
      console.log(new Date().getFullYear() - moment(e).format('YYYY'))
      // this.form.setFieldsValue({age:(new Date().getFullYear() - moment(e).format('YYYY')) +''})
      this.age = new Date().getFullYear() - moment(e).format('YYYY')
    },
    fetchIdCard() {
      //性别
      initDictOptions('sex').then((res) => {
        if (res.success) {
          this.sexList = res.result
        } else {
          this.$message.warning(res.message)
        }
      })
      var that = this
      that.form.setFieldsValue({ national: '' })
      that.form.setFieldsValue({ birthday: null })
      that.form.setFieldsValue({ sex: '' })
      that.age = ''
      that.form.setFieldsValue({ nativePlace: '' })
      that.form.setFieldsValue({ idNumber: '' })
      that.form.setFieldsValue({ issuingAuthority: '' })
      that.form.setFieldsValue({ userName: '' })
      this.dateRangeShen = []
      this.photoZ = ''
      this.photoF = ''
      ////1.声明异步对象
      var xhr = false
      //2.根据浏览器类型，创建异步对象
      if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest()
      } else {
        xhr = new ActiveXObject('Microsoft.XMLHTTP')
      }
      //4.拼写url，把get请求传递的参数拼接到url后边
      var url = 'http://localhost:8989/api/ReadMsg?waitTime=3&readOnce=1&cardImg=1'
      //5.打开异步对象，并设置参数
      xhr.open('get', url, true)
      //6.设置setRequestHeader，不使用缓存数据
      // xhr.setRequestHeader("If-Modified-Since", "0");
      //7.设置回调函数
      xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
          console.log(JSON.parse(xhr.responseText))
          var res = JSON.parse(xhr.responseText)
          that.form.setFieldsValue({ realname: res.name }) //1
          if (res.sex == '男') {
            that.form.setFieldsValue({ sex: '1' }) //2
          } else if (res.sex == '女') {
            that.form.setFieldsValue({ sex: '2' })
          } else {
            that.form.setFieldsValue({ sex: '' })
          }
          // that.sex = res.sex
          that.form.setFieldsValue({ national: res.nation }) //3
          if (res.born) {
            that.form.setFieldsValue({ birthday: that.getDateType(res.born) }) //4
          }
          if (that.form.getFieldValue('birthday')) {
            // that.age = new Date() - res.born.slice(0, 4)   //5
            that.age = new Date().getFullYear() - moment(that.form.getFieldValue('birthday')).format('YYYY') //5
          } else {
            that.age = null
          }
          that.form.setFieldsValue({ nativePlace: res.address }) //6
          that.form.setFieldsValue({ idCardNumber: res.cardno }) //7
          if (res.userlifeb && res.userlifeb) {
            //8,9
            if (res.userlifee === '长期') {
              console.log(
                moment(res.userlifeb.slice(0, 4) * 1 + 100 + res.userlifeb.slice(4, 6) + '-' + res.userlifeb.slice(6))
              )
              that.dateRangeShen = [
                that.getDateType(res.userlifeb),
                moment(
                  res.userlifeb.slice(0, 4) * 1 + 100 + '-' + res.userlifeb.slice(4, 6) + '-' + res.userlifeb.slice(6)
                ),
              ]
            } else {
              that.dateRangeShen = [that.getDateType(res.userlifeb), that.getDateType(res.userlifee)]
            }
          }
          that.form.setFieldsValue({ issuingAuthority: res.police }) //10
          that.photoZ = res.frontImg //12
          that.photoF = res.backImg //13
          that.hadPhoto = false
          that.hadPhotoZ = false
          that.hadPhotoF = false
        } else {
          // that.$message.error('请检查读卡设备！')
        }
      }
      //4.发送异步请求
      xhr.send(null)
    },
    getDateType(e) {
      console.log(e.slice(0, 4) + '-' + e.slice(4, 6) + '-' + e.slice(6))
      return moment(e.slice(0, 4) + '-' + e.slice(4, 6) + '-' + e.slice(6))
    },
    handleSubmit() {
      const that = this
      // 触发表单验证
      let validate = false
      this.form.validateFields((err, values) => {
        if (!err) {
          if (validate == true) {
            return
          }
          that.confirmLoading = true
          let formData = Object.assign(this.model, values)
          if (!formData.birthday) {
            formData.birthday = ''
          } else {
            //生日默认为中午12点 避免夏令制问题出现
            formData.birthday = formData.birthday.format('YYYY-MM-DD') + ' 12:00:00'
          }
          if (this.dateRangeShen.length != 0) {
            formData.validityBegin = this.dateRangeShen[0].format('YYYY-MM-DD') //身份证有效期开始时间
            formData.validityEnd = this.dateRangeShen[1].format('YYYY-MM-DD') //身份证有效期结束时间
          } else {
            formData.validityBegin = ''
            formData.validityEnd = ''
          }
          formData.idCardFront = this.photoZ //身份证正面照
          formData.idCardBack = this.photoF //身份证反面照
          formData.id = this.id
          console.log(formData)
          putAction(this.url.update, formData)
            .then((res) => {
              console.log(res)
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
              that.close()
            })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.form.resetFields()
      this.photoZ = ''
      this.photoF = ''
      this.age = ''
      this.dateRangeShen = []
      this.hadPhotoZ = true
      this.hadPhotoF = true
    },
    open(record) {
      this.visible = true
      this.id = record.id
    },
  },
}
</script>
<style>
.had {
  border: none;
}
.nohad {
  border: 1px solid #ccc;
}
</style>